//
//  EditSaveAddressVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/2/24.
//  Copyright © 2020 cat. All rights reserved.
//

#import "EditSaveAddressVC.h"
@import CoreLocation;

@interface EditSaveAddressVC ()<UIPickerViewDelegate, UIPickerViewDataSource,CLLocationManagerDelegate>
{
    UIView *cityPickBack;
    UIPickerView *cityPicker;
    //省市区-数组
    NSArray *province;
    NSArray *city;
    NSArray *district;
    
    //省市区-字符串
    NSString *provinceStr;
    NSString *cityStr;
    NSString *districtStr;
    NSDictionary *areaDic;
    NSString *selectedProvince;

    NSString *normalProvince;
    NSString *normalCity;
    NSString *normalDistrict;
    CLLocationManager   *_lbsManager;

}
@property (nonatomic, strong)MyTextView *nameText;
@property (nonatomic, strong)MyTextView *phoneText;
@property (nonatomic, strong)MyTextView *areaText;
@property (nonatomic, strong)MyTextView *addressText;
@end

@implementation EditSaveAddressVC
-(void)initData{
    
    provinceStr = self.addModel.receiver_province;
    cityStr = self.addModel.receiver_city;
    districtStr = self.addModel.receiver_area;
    normalProvince = @"";
    normalCity = @"";
    normalDistrict = @"";

    NSBundle *bundle = [NSBundle mainBundle];
    NSString *plistPath = [bundle pathForResource:@"area" ofType:@"plist"];
    areaDic = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

    NSArray *components = [areaDic allKeys];
    NSArray *sortedArray = [components sortedArrayUsingComparator: ^(id obj1, id obj2) {
        
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];

    NSMutableArray *provinceTmp = [[NSMutableArray alloc] init];
    for (int i=0; i<[sortedArray count]; i++) {
        NSString *index = [sortedArray objectAtIndex:i];
        NSArray *tmp = [[areaDic objectForKey: index] allKeys];
        [provinceTmp addObject: [tmp objectAtIndex:0]];
    }
    //---> //rk_3-7 修复首次加载问题
    province = [[NSArray alloc] initWithArray: provinceTmp];
    NSString *index = [sortedArray objectAtIndex:0];
    //NSString *selected = [province objectAtIndex:0];
    selectedProvince = [province objectAtIndex:0];
    NSDictionary *proviceDic = [NSDictionary dictionaryWithDictionary: [[areaDic objectForKey:index]objectForKey:selectedProvince]];

    NSArray *cityArray = [proviceDic allKeys];
    NSDictionary *cityDic = [NSDictionary dictionaryWithDictionary: [proviceDic objectForKey: [cityArray objectAtIndex:0]]];
    //city = [[NSArray alloc] initWithArray: [cityDic allKeys]];

    NSArray *citySortedArray = [cityArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;//递减
        }
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;//上升
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    NSMutableArray *m_array = [[NSMutableArray alloc] init];
    for (int i=0; i<[citySortedArray count]; i++) {
        NSString *index = [citySortedArray objectAtIndex:i];
        NSArray *temp = [[proviceDic objectForKey: index] allKeys];
        [m_array addObject: [temp objectAtIndex:0]];
    }
    city = [NSArray arrayWithArray:m_array];
    //<-----------

    NSString *selectedCity = [city objectAtIndex: 0];
    district = [[NSArray alloc] initWithArray: [cityDic objectForKey: selectedCity]];
    [self location];

}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text =YZMsg(@"编辑收货地址");
//    self.view.backgroundColor = Normal_BackColor;
    self.view.backgroundColor = RGB(250, 250, 250);
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    [self initData];
    [self createUI];
    
    UIButton *saveBtn = [UIButton buttonWithType:0];
    saveBtn.frame = CGRectMake(12, _window_height-60, _window_width-24, 40);
    [saveBtn setBackgroundColor:Pink_Cor];
    [saveBtn setTitle:YZMsg(@"保存") forState:0];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:0];
    saveBtn.titleLabel.font  = [UIFont systemFontOfSize:14];
    saveBtn.layer.cornerRadius = 5;
    saveBtn.layer.masksToBounds = YES;
    [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];
}

-(void)createUI{
    UIView *backView = [[UIView alloc]init];
    backView.frame = CGRectMake(0, 64+statusbarHeight, _window_width, 250);
    backView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:backView];
    
    for (int i = 0; i < 4; i ++) {
        if (i <= 2) {
            MyTextView *mt = [[MyTextView alloc]init];
            mt.frame = CGRectMake(12, 10+i *50, _window_width-24, 30);
            mt.text = [NSString stringWithFormat:@"%@%i%@",YZMsg(@"这是第"),i,YZMsg(@"行")];
            mt.font = [UIFont systemFontOfSize:14];
            mt.textColor = [UIColor blackColor];
            mt.backgroundColor = [UIColor clearColor];
            [backView addSubview:mt];
            
            UILabel *line = [[UILabel alloc]init];
            line.frame = CGRectMake(12, mt.bottom+10, _window_width-24, 1);
            line.backgroundColor = RGB(245, 245, 245);
            [backView addSubview:line];
            
            switch (i) {
                case 0:
                    self.nameText = mt;
                    self.nameText.text = self.addModel.receiver;
                    break;
                case 1:
                    self.phoneText = mt;
                    self.phoneText.text = self.addModel.receiver_phone;
                    break;
                case 2:{
                    self.areaText = mt;
                    self.areaText.userInteractionEnabled = NO;
                    self.areaText.text = [NSString stringWithFormat:@"%@ %@ %@",self.addModel.receiver_province,self.addModel.receiver_city,self.addModel.receiver_area];
                    UIImageView *rightImg = [[UIImageView alloc]init];
                    rightImg.frame = CGRectMake(_window_width-30, 17+i *50, 16, 16);
                    rightImg.image = [UIImage imageNamed:@"shop_right"];
                    [backView addSubview:rightImg];
                    
                    UIButton *selectAdd = [UIButton buttonWithType:0];
                    selectAdd.frame = mt.frame;
                    [selectAdd addTarget:self action:@selector(selectAddressClick) forControlEvents:UIControlEventTouchUpInside];
                    [backView addSubview:selectAdd];
                }
                    break;

                default:
                    break;
            }
        }else{
            MyTextView *mt = [[MyTextView alloc]init];
            mt.frame = CGRectMake(12, 10+i *50, _window_width-24, 80);
            mt.font = [UIFont systemFontOfSize:14];
            mt.backgroundColor = UIColor.whiteColor;
            mt.textColor = [UIColor blackColor];
            [backView addSubview:mt];
            self.addressText = mt;
            self.addressText.text = self.addModel.receiver_address;
        }
    }
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing: YES];
    cityPickBack.hidden = YES;

}
#pragma mark------保存--------
-(void)saveBtnClick{
    NSString *url = [purl stringByAppendingFormat:@"?service=Seller.upReceiverAddress"];
    
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];
    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"receiver":self.nameText.text,
                          @"receiver_phone":self.phoneText.text,
                          @"receiver_province":provinceStr,
                          @"receiver_city":cityStr,
                          @"receiver_area":districtStr,
                          @"receiver_address":self.addressText.text,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };
    
    [WYNetworking postWithUrl:@"Seller.upReceiverAddress" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            if (self.sellAddressEvent) {
                self.sellAddressEvent();
            }
            [MBProgressHUD showError:msg];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];

}
#pragma mark------选择地址--------

-(void)selectAddressClick{
    [self.view endEditing:YES];
    if (!cityPickBack) {
        cityPickBack = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        cityPickBack.backgroundColor = RGB_COLOR(@"#000000", 0.3);
        [self.view addSubview:cityPickBack];
        
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(15, _window_height-240, _window_width-30, 40)];
        titleView.backgroundColor = [UIColor whiteColor];
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:titleView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = titleView.bounds;
        maskLayer.path = maskPath.CGPath;
        titleView.layer.mask = maskLayer;
        [cityPickBack addSubview:titleView];
        
        [PublicObj lineViewWithFrame:CGRectMake(0,titleView.height-1, titleView.width, 1) andColor:RGB(240, 240, 240) andView:titleView];

        UIButton *cancleBtn = [UIButton buttonWithType:0];
        cancleBtn.frame = CGRectMake(10, 0, 80, 40);
        cancleBtn.tag = 100;
        [cancleBtn setTitle:YZMsg(@"取消") forState:0];
        cancleBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [cancleBtn setTitleColor:[UIColor blackColor] forState:0];
        [cancleBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:cancleBtn];
        UIButton *sureBtn = [UIButton buttonWithType:0];
        sureBtn.frame = CGRectMake(titleView.width-90, 0, 80, 40);
        sureBtn.tag = 101;
        [sureBtn setTitle:YZMsg(@"确定") forState:0];
        sureBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [sureBtn setTitleColor:Pink_Cor forState:0];
        [sureBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:sureBtn];
        
        UILabel *titleLb = [[UILabel alloc]initWithFrame:CGRectMake(titleView.width/2-90, 0, 180, 40)];
        titleLb.font = [UIFont systemFontOfSize:15];
        titleLb.textColor = [UIColor blackColor];
        titleLb.textAlignment = NSTextAlignmentCenter;
        titleLb.text = YZMsg(@"选择地区");
        [titleView addSubview:titleLb];

        cityPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(15, _window_height-200, _window_width-30, 190)];
        cityPicker.backgroundColor = [UIColor whiteColor];
        cityPicker.delegate = self;
        cityPicker.dataSource = self;
        cityPicker.showsSelectionIndicator = YES;
        [cityPicker selectRow: 0 inComponent: 0 animated: YES];
        [cityPickBack addSubview:cityPicker];
        
        UIBezierPath *maskPath2 = [UIBezierPath bezierPathWithRoundedRect:cityPicker.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
        CAShapeLayer *maskLayer2 = [[CAShapeLayer alloc] init];
        maskLayer2.frame = cityPicker.bounds;
        maskLayer2.path = maskPath2.CGPath;
        cityPicker.layer.mask = maskLayer2;
        [self setLocationAddress];

    }else{
        cityPickBack.hidden = NO;
    }

}
- (void)cityCancleOrSure:(UIButton *)button{
    if (button.tag == 100) {
        //return;
    }else{
        NSInteger provinceIndex = [cityPicker selectedRowInComponent: 0];
        NSInteger cityIndex = [cityPicker selectedRowInComponent: 1];
        NSInteger districtIndex = [cityPicker selectedRowInComponent: 2];
        
        provinceStr = [province objectAtIndex: provinceIndex];
        cityStr = [city objectAtIndex: cityIndex];
        districtStr = [district objectAtIndex:districtIndex];
        NSString *dizhi = [NSString stringWithFormat:@"%@ %@ %@",provinceStr,cityStr,districtStr];
        self.areaText.text = dizhi;
        
    }
    cityPickBack.hidden = YES;
    
}
#pragma mark- Picker Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    if (pickerView == cityPicker) {
        return 3;
    }
    return 0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (pickerView == cityPicker) {
        if (component == 0) {
            return [province count];
        }
        else if (component == 1) {
            return [city count];
        }
        else {
            return [district count];
        }
    }else{
        return 100;
    }
}


#pragma mark- Picker Delegate Methods

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (pickerView == cityPicker) {
        if (component == 0) {
            return [province objectAtIndex: row];
        }
        else if (component == 1) {
            return [city objectAtIndex: row];
        }
        else {
            return [district objectAtIndex: row];
        }
    }else{
        return nil;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (pickerView == cityPicker) {
        if (component == 0) {
            selectedProvince = [province objectAtIndex: row];
            NSDictionary *tmp = [NSDictionary dictionaryWithDictionary: [areaDic objectForKey: [NSString stringWithFormat:@"%ld", row]]];
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary: [tmp objectForKey: selectedProvince]];
            NSArray *cityArray = [dic allKeys];
            NSArray *sortedArray = [cityArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
                
                if ([obj1 integerValue] > [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedDescending;//递减
                }
                if ([obj1 integerValue] < [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedAscending;//上升
                }
                return (NSComparisonResult)NSOrderedSame;
            }];
            
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (int i=0; i<[sortedArray count]; i++) {
                NSString *index = [sortedArray objectAtIndex:i];
                NSArray *temp = [[dic objectForKey: index] allKeys];
                [array addObject: [temp objectAtIndex:0]];
            }
            
            city = [[NSArray alloc] initWithArray: array];
            
            NSDictionary *cityDic = [dic objectForKey: [sortedArray objectAtIndex: 0]];
            district = [[NSArray alloc] initWithArray: [cityDic objectForKey: [city objectAtIndex: 0]]];
            [cityPicker selectRow: 0 inComponent: 1 animated: YES];
            [cityPicker selectRow: 0 inComponent: 2 animated: YES];
            [cityPicker reloadComponent: 1];
            [cityPicker reloadComponent: 2];
            
        } else if (component == 1) {
            NSString *provinceIndex = [NSString stringWithFormat: @"%ld", [province indexOfObject: selectedProvince]];
            NSDictionary *tmp = [NSDictionary dictionaryWithDictionary: [areaDic objectForKey: provinceIndex]];
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary: [tmp objectForKey: selectedProvince]];
            NSArray *dicKeyArray = [dic allKeys];
            NSArray *sortedArray = [dicKeyArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
                
                if ([obj1 integerValue] > [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedDescending;
                }
                
                if ([obj1 integerValue] < [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedAscending;
                }
                return (NSComparisonResult)NSOrderedSame;
            }];
            
            NSDictionary *cityDic = [NSDictionary dictionaryWithDictionary: [dic objectForKey: [sortedArray objectAtIndex: row]]];
            NSArray *cityKeyArray = [cityDic allKeys];
            
            district = [[NSArray alloc] initWithArray: [cityDic objectForKey: [cityKeyArray objectAtIndex:0]]];
            [cityPicker selectRow: 0 inComponent: 2 animated: YES];
            [cityPicker reloadComponent: 2];
        }
    }else{
        
    }
    
}


- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    if (component == 0) {
        return 80;
    }
    else if (component == 1) {
        return 100;
    }
    else {
        return 115;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *myView = nil;
    if (pickerView == cityPicker) {
        if (component == 0) {
            myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, _window_width/3, 30)];
            myView.textAlignment = NSTextAlignmentCenter;
            myView.text = [province objectAtIndex:row];
            myView.font = [UIFont systemFontOfSize:14];
            myView.backgroundColor = [UIColor clearColor];
        }
        else if (component == 1) {
            myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, _window_width/3, 30)];
            myView.textAlignment = NSTextAlignmentCenter;
            myView.text = [city objectAtIndex:row];
            myView.font = [UIFont systemFontOfSize:14];
            myView.backgroundColor = [UIColor clearColor];
        }
        else {
            myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, _window_width/3, 30)];
            myView.textAlignment = NSTextAlignmentCenter;
            myView.text = [district objectAtIndex:row];
            myView.font = [UIFont systemFontOfSize:14];
            myView.backgroundColor = [UIColor clearColor];
        }
    }
    return myView;
}
-(void)setLocationAddress{
    int provinceIndex = 0;
    int cityIndex = 0;

    NSArray *components = [areaDic allKeys];
    NSArray *sortedArray = [components sortedArrayUsingComparator: ^(id obj1, id obj2) {
        
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    NSMutableArray *provinceTmp = [[NSMutableArray alloc] init];
    for (int i=0; i<[sortedArray count]; i++) {
        NSString *index = [sortedArray objectAtIndex:i];
        NSArray *tmp = [[areaDic objectForKey: index] allKeys];
        [provinceTmp addObject: [tmp objectAtIndex:0]];
    }

    if (normalProvince.length > 0) {
        selectedProvince = normalProvince;

        for (int i = 0; i < province.count; i ++) {
            if ([normalProvince isEqual:province[i]]) {
                provinceIndex = i;
                NSString *index = [sortedArray objectAtIndex:i];

                NSDictionary *proviceDic = [NSDictionary dictionaryWithDictionary: [[areaDic objectForKey:index]objectForKey:normalProvince]];
                NSArray *cityArray = [proviceDic allKeys];
                NSDictionary *cityDic = [NSDictionary dictionaryWithDictionary: [proviceDic objectForKey: [cityArray objectAtIndex:i]]];

                NSArray *citySortedArray = [cityArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
                    if ([obj1 integerValue] > [obj2 integerValue]) {
                        return (NSComparisonResult)NSOrderedDescending;//递减
                    }
                    if ([obj1 integerValue] < [obj2 integerValue]) {
                        return (NSComparisonResult)NSOrderedAscending;//上升
                    }
                    return (NSComparisonResult)NSOrderedSame;
                }];
                NSMutableArray *m_array = [[NSMutableArray alloc] init];
                for (int i=0; i<[citySortedArray count]; i++) {
                    NSString *index = [citySortedArray objectAtIndex:i];
                    NSArray *temp = [[proviceDic objectForKey: index] allKeys];
                    [m_array addObject: [temp objectAtIndex:0]];
                }
               NSArray *cityArr = [NSArray arrayWithArray:m_array];
                city =[NSArray arrayWithArray:m_array];
                for (int j = 0; j < cityArr.count; j ++) {
                    if ([normalCity isEqual:cityArr[j]]) {
                        cityIndex = j;
                        NSString *keys = [NSString stringWithFormat:@"%d",cityIndex];
                        NSDictionary *dicssss = [NSDictionary dictionaryWithDictionary: [proviceDic objectForKey: keys]];

                        NSString *selectedCity = [cityArr objectAtIndex: j];
                        district = [[NSArray alloc] initWithArray: [dicssss objectForKey: selectedCity]];

                        NSArray * districtArr = [[NSArray alloc] initWithArray: [dicssss objectForKey: selectedCity]];
                        for (int k = 0; k <districtArr.count; k ++) {
                            if ([normalDistrict isEqual:districtArr[k]]) {
                                [cityPicker selectRow: provinceIndex inComponent: 0 animated: YES];
                                [cityPicker reloadComponent: 1];

                                [cityPicker selectRow: cityIndex inComponent: 1 animated: YES];
                                [cityPicker reloadComponent: 2];

                                [cityPicker selectRow: k inComponent: 2 animated: YES];
                            }
                        }
                    }
                }
            }
        }
    }
    NSLog(@"province===:%@  \n city:%@   \ndistrict:%@",province,city,district);
}
-(void)location{
    if (!_lbsManager) {
        _lbsManager = [[CLLocationManager alloc] init];
        [_lbsManager setDesiredAccuracy:kCLLocationAccuracyBest];
        _lbsManager.delegate = self;
        // 兼容iOS8定位
        CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

        if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
            NSLog(@"请打开您的位置服务!");
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

               UIAlertController *alertContro = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:YZMsg(@"打开“定位服务”来允许“%@”确定您的位置"),[infoDictionary objectForKey:@"CFBundleDisplayName"]] preferredStyle:UIAlertControllerStyleAlert];
               UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:YZMsg(@"设置") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
               }];
               [alertContro addAction:cancleAction];
            [cancleAction setValue:Normal_Color forKey:@"_titleTextColor"];
               UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                   
               }];
               [alertContro addAction:sureAction];
            [sureAction setValue:[UIColor blackColor] forKey:@"_titleTextColor"];

            [[[YBBaseAppDelegate sharedAppDelegate]topViewController]presentViewController:alertContro animated:YES completion:nil];

        }else{

            SEL requestSelector = NSSelectorFromString(@"requestWhenInUseAuthorization");
            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined && [_lbsManager respondsToSelector:requestSelector]) {
                [_lbsManager requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
            } else {
                [_lbsManager startUpdatingLocation];
            }
        }
    }
}
- (void)stopLbs {
    [_lbsManager stopUpdatingHeading];
    _lbsManager.delegate = nil;
    _lbsManager = nil;
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusRestricted || status == kCLAuthorizationStatusDenied) {
        [self stopLbs];
    } else {
        [_lbsManager startUpdatingLocation];
    }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    [self stopLbs];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *newLocatioin = locations[0];
    //zl---待修改
//    liveCity *cityU = [cityDefault myProfile];
//    cityU.lat = [NSString stringWithFormat:@"%f",newLocatioin.coordinate.latitude];
//    cityU.lng = [NSString stringWithFormat:@"%f",newLocatioin.coordinate.longitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocatioin completionHandler:^(NSArray *placemarks, NSError *error) {
        if (!error)
        {
            CLPlacemark *placeMark = placemarks[0];
            NSString *addr = [NSString stringWithFormat:@"%@%@%@",placeMark.administrativeArea,placeMark.locality,placeMark.subLocality];
            NSLog(@"hhhhhhhh----:%@", addr);
            normalProvince =placeMark.administrativeArea;
            normalCity = placeMark.locality;
            normalDistrict = placeMark.subLocality;
        }
    }];
     [self stopLbs];
}

@end
